<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => {
          unfoldFlag = v;
        }
          ">
      </SearchForm>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange" @sort-change="sortChange" :total="total">
        <template v-slot:personName="{ row }">
          <span>{{ row.person ? row.person.name || "--" : "--" }}</span>
        </template>
        <template v-slot:personGender="{ row }">
          <span>{{ row.person ? row.person.gender || "--" : "--" }}</span>
        </template>
        <template v-slot:personPhone="{ row }">
          <span>{{ row.person ? row.person.phone || "--" : "--" }}</span>
        </template>
        <template v-slot:personLandline="{ row }">
          <span>{{ row.person ? row.person.landline || "--" : "--" }}</span>
        </template>
        <template v-slot:departmentName="{ row }">
          <span>{{
            row.department ? row.department.departmentName || "--" : "--"
          }}</span>
        </template>
        <template v-slot:postName="{ row }">
          <span>{{ row.post ? row.post.postName || "--" : "--" }}</span>
        </template>
        <template v-slot:status="{ row }">
          <el-switch v-model="row.status" active-color="#13ce66" inactive-color="#ff4949"
            @change="() => handleChangeStatus(row)">
          </el-switch>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'人员'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";
import EnumSlot from "@/components/EnumSlot";
import AddEdit from "./components/addEdit";
import staffManage from "@/api/basicInformationOperate/staffManage";
import departmentManage from "@/api/basicInformationOperate/departmentManage";
import stationManage from "@/api/basicInformationOperate/stationManage";
export default {
  components: {
    MainSlot,
    Pagination,
    SearchForm,
    TableData,
    BtnSlot,
    AddEdit,
    EnumSlot,
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      unfoldFlag: false,
      addEditFlag: "add",
      departmentNo: null,
      formData: {},
      searchFormData: {
        status: true,
      },
      selectionList: [],
      page: 1,
      size: 10,
      total: 10,
      selectIndex: 0,
      enumList: [
        {
          label: "在职",
          status: true,
        },
        {
          label: "离职",
          status: false,
        },
      ],
      btnList: ["add", "delete"],
      dataList: [],
      tableThead: [
        { isShow: true, label: "员工姓名", slotName: "personName" },
        { isShow: true, label: "性别", slotName: "personGender" },
        { isShow: true, label: "手机号", slotName: "personPhone" },
        { isShow: true, label: "座机号", slotName: "personLandline" },
        { isShow: true, label: "部门", slotName: "departmentName" },
        { isShow: true, label: "岗位", slotName: "postName" },
        { isShow: true, label: "状态", slotName: "status" },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "200",
          cols: [
            {
              label: "编辑",
              type: "primary",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "删除",
              type: "danger",
              flag: "delete",
              handleRow: this.handleRow,
            },
          ],
        },
      },
      departmentList: [],
      stationList: [],
      formItemList: [
        {
          label: "部门",
          type: "select",
          selectOptions: [],
          param: "departmentNo",
          defaultSelect: "", // 下拉框默认选中项
          multiple: false,
          isShow: true,
        },
        {
          label: "岗位",
          type: "select",
          selectOptions: [],
          param: "postNo",
          defaultSelect: "", // 下拉框默认选中项
          multiple: false,
          isShow: true,
        },
      ],
    };
  },
  mounted() {
    this.queryPageByCondition();
    this.initOptionsData();
  },
  methods: {
    async initOptionsData() {
      let { data: departmentList } = await departmentManage.queryByCondition(
        {}
      );
      this.departmentList = departmentList || [];
      let { data: stationList } = await stationManage.queryByCondition({});
      this.stationList = stationList || [];
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = [];
      list.forEach((item, index) => {
        if (item.param == "departmentNo") {
          let selectOptions = this.departmentList.map((data) => {
            return {
              text: data.departmentName,
              value: data.departmentNo,
            };
          });
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        }
        if (item.param == "postNo") {
          let selectOptions = this.stationList.filter((data) => {
            data.text = data.postName;
            data.value = data.postNo;
            return this.searchFormData.departmentNo == data.departmentNo;
          });
          item.defaultSelect = this.searchFormData["departmentNo"]
            ? this.searchFormData[item.param]
            : "";
          item.selectOptions = this.searchFormData["departmentNo"]
            ? selectOptions
            : "";
        }
      });

      this.$nextTick(() => {
        this.$set(this, "formItemList", list);
      });
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          organizationNo: sessionStorage.organizationNo,
          ...this.searchFormData,
        },
      };
      staffManage
        .queryPageByCondition(params)
        .then((res) => {
          if (res.code == 1) {
            this.dataList = res.data.content || [];
            this.total = res.data.totalElements;
            if (res.data.totalPages && this.page > res.data.totalPages) {
              this.page = res.data.totalPages;
              this.queryPageByCondition();
            }
          } else {
            this.$message.warning(res.msg || "分页查询失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //搜索
    search(data) {
      this.page = 1;
      console.log(data, "datadatadatadatadatadata");
      if (data.departmentNo) {
        this.searchFormData.departmentNo = data.departmentNo
        // stationManage
        //   .queryByCondition({ departmentNo: data.departmentNo })
        //   .then((res) => {
        //     this.stationList = res.data;
        //   });
      }

      this.searchFormData = { ...this.searchFormData, ...data };
      this.setFormOptions();
      this.queryPageByCondition();
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      this.page = 1;
      this.selectIndex = enumInfo.index || 0;
      this.searchFormData.status = enumInfo.data.status;
      this.queryPageByCondition();
      console.log(enumInfo);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "edit") {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData));
      } else if (item.flag == "delete") {
        this.delList([rowData]);
      }
      this.addEditFlag = item.flag;
    },
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    delList(deleteList = [], key = "employeeNo") {
      let list = [];
      deleteList.forEach((item) => {
        list.push(item[key]);
      });
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await staffManage.delListById(list);
          if (res.code == 1) {
            this.$message.success(res.msg || "删除成功");
            this.queryPageByCondition();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 排序方法
    sortChange(val) {
      console.log(val);
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.dialogVisible = true;
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.delList(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },
    //关闭弹窗
    closeDialog() {
      this.page = 1;
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
    async handleChangeStatus(row) {
      console.log(row);
      let res = await staffManage.edit({ ...row });
      if (res.code == 1) {
        this.$message.success(res.msg || "操作成功");
        this.queryPageByCondition();
      } else {
        this.$message.warning(res.msg || "操作失败");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.pointer {
  cursor: pointer;
}
</style>